﻿using Devil.Persistent;
using LitJson;
using System.Collections.Generic;

namespace GameToolkit.Task
{
    public class PersistentTaskGraphBlock : IRestorablePersistentBlock
    {
        EPersistentType IPersistentBlock.BlockType => EPersistentType.GamePlay;
        public int Version => 1;

        public string BlockName => "PB_TaskGraph";

        object IPersistentBlock.CreateInstance(JsonData content)
        {
            var asset = (string)content["asset"];
            var id = (int)content["id"];
            return new TaskGraph(asset, id);
        }

        void IPersistentBlock.GatherPersistentDatas(ICollection<object> datas)
        {
        }

        bool IPersistentBlock.IsInstanceSerializer(object instance)
        {
            return instance is TaskGraph;
        }

        void IPersistentBlock.OnDeserializeParallel(object instance, JsonData content)
        {
            if (instance is TaskGraph graph)
                ((IJsonSerializable)graph).OnDeserialize(content);
        }

        JsonData IPersistentBlock.OnSerializeParallel(object instance)
        {
            if (instance is TaskGraph graph)
                return ((IJsonSerializable)graph).OnSerialize();
            else
                return null;
        }

        void IRestorablePersistentBlock.RestorePersistentDatas(ICollection<object> datas, ICollection<object> referenced)
        {
            foreach (var obj in referenced)
            {
                if (obj is TaskGraph graph)
                    graph.RestoreParentGraph();
            }
            foreach (var obj in referenced)
            {
                if (obj is TaskGraph graph)
                    graph.RestoreSyncLock();
            }
        }

    }
}
